/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.common.util;

import com.hsxxherp.key.common.error.ErrorCode;
import com.hsxxherp.key.common.exception.BusinessException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * AESUtils 工具类
 *
 * @author Mark·虎克 (2486970363@qq.com)
 */
public class AESUtil {

    /**
     * AES 算法名称
     */
    private static final String ALGORITHM = "AES";

    /**
     * AES 默认密码长度
     */
    private static final int DEFAULT_KEY_SIZE = 128;

    private AESUtil() {
        // 私有构造函数，防止实例化
    }

    /**
     * 生成 AES 密钥
     *
     * @return 生成的密钥的 Base64 编码字符串
     */
    public static String generateKey() {
        return generateKey(DEFAULT_KEY_SIZE);
    }

    /**
     * 生成 AES 密钥
     *
     * @param keySize 密钥长度，可以是 128、192 或 256
     * @return 生成的密钥的 Base64 编码字符串
     */
    public static String generateKey(int keySize) {
        try {
            KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
            keyGen.init(keySize, new SecureRandom());
            SecretKey secretKey = keyGen.generateKey();
            return Base64.getEncoder().encodeToString(secretKey.getEncoded());
        } catch (Exception e) {
            throw new BusinessException("AES秘钥生成失败", e).setCode(ErrorCode.CODE_100001);
        }

    }

    /**
     * ECB 模式加密
     *
     * @param plaintext 明文数据
     * @param key       Base64 编码的密钥
     * @return 加密后的 Base64 编码字符串
     */
    public static String encryptECB(String plaintext, String key) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(key);
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new BusinessException("AES加密失败", e).setCode(ErrorCode.CODE_100002);
        }

    }

    /**
     * ECB 模式解密
     *
     * @param ciphertext 加密后的 Base64 编码字符串
     * @param key        Base64 编码的密钥
     * @return 解密后的明文数据
     */
    public static String decryptECB(String ciphertext, String key) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(key);
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM + "/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decodedBytes = Base64.getDecoder().decode(ciphertext);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new BusinessException("AES解密失败", e).setCode(ErrorCode.CODE_100003);
        }
    }

    /**
     * CBC 模式加密
     *
     * @param plaintext 明文数据
     * @param key       Base64 编码的密钥
     * @param iv        初始化向量的 Base64 编码字符串
     * @return 加密后的 Base64 编码字符串
     * @throws Exception 加密过程中可能抛出的异常
     */
    public static String encryptCBC(String plaintext, String key, String iv) throws Exception {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(key);
            byte[] ivBytes = Base64.getDecoder().decode(iv);
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            Cipher cipher = Cipher.getInstance(ALGORITHM + "/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new BusinessException("AES加密失败", e).setCode(ErrorCode.CODE_100002);
        }
    }

    /**
     * CBC 模式解密
     *
     * @param ciphertext 加密后的 Base64 编码字符串
     * @param key        Base64 编码的密钥
     * @param iv         初始化向量的 Base64 编码字符串
     * @return 解密后的明文数据
     * @throws Exception 解密过程中可能抛出的异常
     */
    public static String decryptCBC(String ciphertext, String key, String iv) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(key);
            byte[] ivBytes = Base64.getDecoder().decode(iv);
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            Cipher cipher = Cipher.getInstance(ALGORITHM + "/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] decodedBytes = Base64.getDecoder().decode(ciphertext);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new BusinessException("AES解密失败", e).setCode(ErrorCode.CODE_100003);
        }
    }

    /**
     * 生成随机的初始化向量（IV）
     *
     * @return 初始化向量的 Base64 编码字符串
     */
    public static String generateIV() {
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);
        return Base64.getEncoder().encodeToString(iv);
    }
}